<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="客户">
            <a-select
              show-search
                placeholder="请选择"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="getcusIdOptions"
                @change="handleChangeCus"
                disabled v-decorator="['cusId', { rules: [{ required: true, message: '请选择客户!' }] }]"
              >
            <a-select-option v-for="t in cusIdOptions" :key="t.value">{{t.text}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol"  :wrapperCol="wrapperCol" label="销售">
          <j-dict-select-tag disabled v-decorator="['userId', { rules: [{ required: true, message: '请选择用户!' }]}]"
           placeholder="请选择用户" :triggerChange=true dictCode="sys_user,realname,id,sales=1 "/>
        </a-form-item>
        <div class="order-item">
          <a-row :gutter="10" style="line-height:30px;">
            <a-col :span="5" class="col-right"><label class="item-label">商品明细</label></a-col>
          </a-row>
          <a-row v-for="(item,index) in productItem"  :key="'item_'+index" :gutter="10" style="line-height:35px;font-size:12px">
              <a-col :span="2" class="col-right"><label>产品</label></a-col>
              <a-col :span="6" class="col-left">
                 <pro-select type=2 :triggerChange=false disabled v-model="item.proId" @input="itemNumChanged"/>
              </a-col>
              <a-col :span="2" class="col-right"><label>数量</label></a-col>
              <a-col :span="3" class="col-left">
                 <a-input-number v-model="item.num" disabled @change="itemNumChanged"/>
              </a-col>
              <a-col :span="2" class="col-right"><label>价格</label></a-col>
              <a-col :span="4" class="col-left">
                <a-input-number v-model="item.price" disabled @change="itemPriceChanged"/>元
              </a-col>
              <a-col :span="3" class="col-left"><label>分成:</label>
                <span class="rateWord">{{item.rate}}%</span>
              </a-col>
          </a-row>
        </div>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"  label="总价">
          <a-input-number disabled v-decorator="[ 'totalPrice', {rules: [{ required: true, message: '请填写商品!' },{ validator: handlePrice}]}]" disabled />元
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-textarea disabled v-decorator="[ 'remark', {}]"></a-textarea>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单状态">
          <j-dict-select-tag disabled v-decorator="[ 'state', {}]" title="状态" dictCode="orderState" placeholder="请选择"
            :triggerChange=true />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分成金额">
          <a-input-number disabled v-model="model.perfPrice" />
        </a-form-item>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import debounce from 'lodash/debounce';
  import ProSelect from '@/views/crm/comp/ProSelect'

  export default {
    name: "OrderMassModal",
    components:{
      ProSelect
    },
    data () {
      this.lastFetchId = 0;
      this.getcusIdOptions = debounce(this.getcusIdOptions, 800);
      return {
        productItem:[],
        cusIdOptions:[],
        fetching:false,
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          add: "/crm/orderMass/add",
          edit: "/crm/orderMass/edit",
          getcusId: "/crm/cus/getcusId",
          getproductId: "/crm/product/getproductId",
        },
      }
    },
    created () {
      this.getcusIdOptions();
      this.listMission();
    },
    watch:{
      // productItem:'calculateTotalAmount'
    },
    methods: {
      look (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        if(record.productItem!=undefined){
          this.productItem=record.productItem;
        }
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'userId','cusId','totalPrice', 'remark', 'state','perfPrice'))
		  //时间格式化
        });

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.calculateTotalAmount();
            let formData = Object.assign(this.model, values);
            //时间格式化
            
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      handlePrice(rule,value,callback){
        if(value==undefined||value==null||value<=0){
          console.log(value);
          callback('请填写商品');
        }
        callback();
      },
      filterOption(input, option) {
        return (
         option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleChangeCus(value) {
            console.log(`selected ${value}`);
             this.getSaleId(value);
      },
      getcusIdOptions(value){
        console.log('getcusIdOptions', value);
        this.lastFetchId += 1;
        const fetchId = this.lastFetchId;
        this.cusIdOptions = [];
        this.fetching = true;
        let param={mobile:value};
      getAction(this.url.getcusId, param)
          .then((res) => {
            if (fetchId !== this.lastFetchId) {       
              return;
            }
            if (res.success) {
             this.cusIdOptions=res.result;
            } else {
              that.$message.warning(res.message)
            }
            this.fetching = false;
          })
          
      },
      deleteItem(item,index){
        this.productItem.splice(index,1);
        if(this.productItem.length<=0){
          this.addItem(this.productItem);
        }
        this.calculateTotalAmount();
      },
      addItem(productItem){
        this.productItem.push({
            proId:"",
            num:"",
            price:"",
          });
      },
      itemPriceChanged(val){
        if(isNaN(val)){
          val=0;
        }
        var pattern = /^\d+.?\d{0,2}$/;
        if(!pattern.test(val))
          val =parseFloat(val).toFixed(2);
       this.calculateTotalAmount();
      },
      itemNumChanged(val){
        if(isNaN(val)){
          val=0;
        }
        this.calculateTotalAmount();
      },
      calculateTotalAmount(){
        var totalPrice=0;
        this.model.productItem =this.productItem.map((item)=>{
            if(item.price && item.num  && !isNaN(item.price) && !isNaN(item.num)){
              totalPrice+=parseFloat(item.price).toFixed(2)*parseInt(item.num);
            }
            return item;
        });
        this.model.totalPrice=parseInt(totalPrice);
        this.form.setFieldsValue(pick(this.model,'totalPrice'))
      },
      getSaleId(value){
        let param={id:value};
        getAction('/crm/cus/getSaleId', param).then((res) => {
            if (res.success) {
              this.model.userId=res.result;
              this.form.setFieldsValue(pick(this.model,'userId'))
            } else {
              that.$message.warning(res.message)
            }
          
          })
      },
      listMission(value){
        getAction('/crm/missionMass/listMission').then((res) => {
            if (res.success) {
              this.missionList=res.result;
            } else {
              that.$message.warning(res.message)
            }
          
          })
      },
    }
  }
</script>

<style lang="less" scoped>
.order-item{
  margin-bottom:7px;
}
.item-label{
  font-weight:bold;
}
.col-right{
  text-align:right;
}
.col-left{
  text-align: left;
}
.rateWord{
  color: red;
}
</style>